// pages/my/wallet/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: 700,
    wallet: getApp().util.fmtPrice(0),
    reachBottomText: null,
    keyword: null,
    isLoading: false,
    listQuery: {
      page: 1,
      limit: 20,
      keyword: '',
      sort: '-gmtCreated'
    },
    walletChangePages: 1,
    walletChanges: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.getSystemInfo({
      success: (res) => {
        let windowHeight = (res.windowHeight * (750 / res.windowWidth));
        if (res.model.search('iPhone X') != -1) {}
        this.setData({
          windowWidth: res.windowWidth,
          scrollHeight: ((windowHeight * 0.6) - (210) * 750 / res.windowWidth)
        })
      }
    })
    this.fetchWallet()
    this.fetchWalletChange()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  fetchWallet() {
    getApp().verifyLogin().then(res => {
      getApp().network.get(getApp().api.getUserWallet, ).then(res => {
        this.setData({
          ...res,
          wallet: getApp().util.fmtPrice(res.wallet)
        })
      })
    })
  },
  pullDownRefresh() {
    this.setData({
      walletChanges: [],
      reachBottomText: null,
      listQuery: {
        ...this.data.listQuery,
        page: 1
      }
    })
    this.fetchWalletChange()
  },
  loadMore() {
    var page = this.data.listQuery.page
    if (page < this.data.walletChangePages) {
      page += 1
      this.setData({
        reachBottomText: null
      })
    } else {
      this.setData({
        reachBottomText: '已经到达最后一页'
      })
      return
    }
    this.setData({
      keyword: null,
      listQuery: {
        ...this.data.listQuery,
        page: page
      }
    })
    this.fetchWalletChange()
  },
  fetchWalletChange() {
    getApp().network.get(getApp().api.memberUserWalletChange, this.data.listQuery).then(res => {
      var walletChanges = []
      for (var item of res.records) {
        item.changeNumber = getApp().util.fmtPrice(item.changeNumber)
        item._gmtCreated = getApp().util.formatTime(item.gmtCreated, 'yyyy-MM-dd hh:mm:ss')

        walletChanges.push(item)
      }

      this.setData({
        isLoading: false,
        walletChanges: this.data.walletChanges.concat(...walletChanges),
        walletChangePages: res.pages
      })
    })
  },
  handleRecharge(){
    wx.switchTab({
      url: '/pages/cashier/pay/index',
    })
  },
  goWithdrawal(){
    wx.navigateTo({
      url: '/pages/my/withdrawal/index',
    })
  }
})